package com.sita.tboard.hitchhike.detail;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.MyTrafficStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.facebook.drawee.view.SimpleDraweeView;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.sita.bike.R;
import com.sita.bike.rest.model.Account;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.support.LocationController;
import com.sita.bike.utils.AccountUtils;
import com.sita.tboard.hitchhike.HitchhikeActivity;
import com.sita.tboard.hitchhike.HitchhikeConstants;
import com.sita.tboard.hitchhike.HitchhikeContentActivity;
import com.sita.tboard.hitchhike.bean.TicketModel;
import com.sita.tboard.hitchhike.bean.TicketStatus;
import com.sita.tboard.hitchhike.helper.HitchhikeNetworkHelper;
import com.sita.tboard.hitchhike.helper.HitchhikePersistHelper;
import com.sita.tboard.hitchhike.listeners.OnHitchhikeAcceptTripPlanListener;
import com.sita.tboard.hitchhike.listeners.OnTicketStatusChangeListener;
import com.sita.tboard.ui.tools.L;
import com.sita.tboard.usermgmt.GetAccountInfoListener;
import com.sita.tboard.usermgmt.helper.UserNetworkHelper;
import com.sita.tboard.util.DateUtils;
import com.sita.tboard.util.TextUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import de.hdodenhof.circleimageview.CircleImageView;

public class DriverTripDetailActivity extends HitchhikeContentActivity
        implements LocationSource, AMapLocationListener, AMap.OnMapLoadedListener {

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.avatar)
    SimpleDraweeView mAvatarView;
    @Bind(R.id.btn_dialer)
    CircleImageView mDialerView;
    @Bind(R.id.nickname)
    TextView mNicknameView;
    @Bind(R.id.time)
    TextView mTimeView;
    @Bind(R.id.from)
    TextView mFromView;
    @Bind(R.id.to)
    TextView mToView;
    @Bind(R.id.map)
    MapView mapView;
    @Bind(R.id.btn_confirm_hitchhike)
    Button btnConfirm;
    @Bind(R.id.btn_pickup_customer)
    Button btnPickup;
    @Bind(R.id.btn_customer_arrive)
    Button btnArrive;

    private TicketModel mTicket;
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private Marker fromMarker;
    private Marker toMarker;
    private boolean isStartLocating;
    private Account customerAccount;

    @SuppressWarnings("unused")
    public static Intent newIntent(TicketModel ticket) {
        Intent intent = new Intent(GlobalContext.getGlobalContext(), DriverTripDetailActivity.class);
        intent.putExtra("ticket", ticket);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hitchhike_driver_trip_detail);
        ButterKnife.bind(this);

        mapView.onCreate(savedInstanceState);

        mTicket = (TicketModel) getIntent().getSerializableExtra("ticket");
        if (mTicket == null) {
            L.e("Does not have a bundled ticket");
            finish();
            return;
        }
        customizeToolbar(mToolbar, R.string.hitchhike_ticket_detail);

        initTicket();
        initCustomer();
        initMap();

    }

    private void initTicket() {
        mTimeView.setText(GlobalContext.getGlobalContext().getString(R.string.departure_time,
                DateUtils.formatDateTime(mTicket.orderDepartureTime)));
        mFromView.setText(GlobalContext.getGlobalContext().getString(R.string.from, mTicket.fromaddress));
        mToView.setText(GlobalContext.getGlobalContext().getString(R.string.to, mTicket.toaddress));
    }

    private void initCustomer() {
        UserNetworkHelper.getInstance().getUserInfo(String.valueOf(mTicket.customId),
                new GetAccountInfoListener() {
                    @Override
                    public void onSuccess(Account account) {
                        customerAccount = account;
                        //Picasso.with(GlobalContext.getGlobalContext()).load(account.mAvatar).into(mAvatarView);
                        mAvatarView.setImageURI(account.mAvatar != null ? Uri.parse(account.mAvatar) : Uri.EMPTY);
                        mNicknameView.setText(account.mNickName);
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        ToastUtils.show(GlobalContext.getGlobalContext(),
                                TextUtils.getThrowableMessage(throwable));
                    }
                });
    }

    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            UiSettings mUiSettings = aMap.getUiSettings();
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_CENTER);
            mUiSettings.setZoomControlsEnabled(true);
            mUiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
            mUiSettings.setMyLocationButtonEnabled(false);
            mUiSettings.setAllGesturesEnabled(true);
            mUiSettings.setCompassEnabled(true);
            aMap.setMyTrafficStyle(new MyTrafficStyle());
            aMap.setMyLocationEnabled(false);
            aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

            MyLocationStyle myLocationStyle = new MyLocationStyle();
            myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            aMap.setMyLocationStyle(myLocationStyle);

            aMap.setOnMapLoadedListener(this);
            aMap.setLocationSource(this);

            aMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        }
    }

    private void setupButtons() {
        if (mTicket.status == TicketStatus.getInstance().UNKNOWN
                || mTicket.status == TicketStatus.getInstance().WAITING) {
            btnConfirm.setVisibility(View.VISIBLE);
            btnPickup.setVisibility(View.GONE);
            btnArrive.setVisibility(View.GONE);
        } else if (mTicket.status == TicketStatus.getInstance().ACCEPTED) {
            btnConfirm.setVisibility(View.GONE);
            btnPickup.setVisibility(View.VISIBLE);
            btnArrive.setVisibility(View.GONE);

            mDialerView.setVisibility(View.VISIBLE);

            LocationController.startTracking(this);
            if (aMap != null) {
                aMap.setMyLocationEnabled(true);
            }
        } else if (mTicket.status == TicketStatus.getInstance().START) {
            btnConfirm.setVisibility(View.GONE);
            btnPickup.setVisibility(View.GONE);
            btnArrive.setVisibility(View.VISIBLE);
        } else if (mTicket.status == TicketStatus.getInstance().UNPAID) {
            btnConfirm.setVisibility(View.GONE);
            btnPickup.setVisibility(View.GONE);
            btnArrive.setVisibility(View.GONE);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                if (mTicket.status == TicketStatus.getInstance().UNKNOWN
                        || mTicket.status == TicketStatus.getInstance().WAITING) {
                    finish();
                } else if (mTicket.status == TicketStatus.getInstance().ACCEPTED
                        || mTicket.status == TicketStatus.getInstance().START
                        || mTicket.status == TicketStatus.getInstance().UNPAID) {
                    startActivity(HitchhikeActivity.newIntent(HitchhikeConstants.TAG_DRIVER_RUNNING));
                    finish();
                }
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        setupButtons();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
            aMap = null;
        }
        LocationController.stopTracking(this);
    }

    /**
     * 开始定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (!isStartLocating) {
            LocationController.startTracking(this);
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        LocationController.stopTracking(this);
    }

    @Override
    public void onMapLoaded() {
        if (!isStartLocating) {
            LocationController.startTracking(this);
        }
        initFromToMarkerLine();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null) {
            mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
        }
        //判断定位是否成功
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            return;
        }
        //是否已经开始定位
        isStartLocating = true;

        //是否开始显示自己，小蓝点
        if (mTicket.status != TicketStatus.getInstance().UNKNOWN
                && mTicket.status != TicketStatus.getInstance().WAITING) {
            //地点的纬度，在-90 与90 之间的double 型数值
            double latitude = aMapLocation.getLatitude();
            //地点的经度，在-180 与180 之间的double 型数值
            double longitude = aMapLocation.getLongitude();
            //角标显示的位置
            LatLng myLatLng = new LatLng(latitude, longitude);
            // 设置地图可视缩放大小
            //aMap.animateCamera(CameraUpdateFactory.changeLatLng(latLng));
            if (fromMarker != null && toMarker != null) {
                LatLngBounds bounds = new LatLngBounds.Builder()
                        .include(fromMarker.getPosition()).include(toMarker.getPosition())
                        .include(myLatLng).build();
                // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
                aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
            }
        }
    }

    private void initFromToMarkerLine() {
        PolylineOptions polylineOptions = new PolylineOptions().width(10).color(GlobalContext.getGlobalContext().getResources()
                .getColor(R.color.app_third_color));
        LatLng fromLatlng = null;
        LatLng toLatlng = null;
        if (fromMarker == null) {
            fromLatlng = new LatLng(mTicket.startLat, mTicket.startLng);
            MarkerOptions markerOptions = new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_a))
                    .draggable(false)
                    .position(fromLatlng);
            fromMarker = aMap.addMarker(markerOptions);

            polylineOptions.add(fromLatlng);
        }
        if (toMarker == null) {
            toLatlng = new LatLng(mTicket.endLat, mTicket.endLng);
            MarkerOptions markerOptions = new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_b))
                    .draggable(false)
                    .position(toLatlng);
            toMarker = aMap.addMarker(markerOptions);

            polylineOptions.add(toLatlng);
        }

        aMap.addPolyline(polylineOptions);

        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(fromLatlng).include(toLatlng).build();
        // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 80));
    }

    @OnClick(R.id.btn_confirm_hitchhike)
    void onClickBtnConfirm() {
        mTicket.status = TicketStatus.getInstance().ACCEPTED;
        HitchhikeNetworkHelper.INSTANCE.driverAcceptTrip(String.valueOf(mTicket.id), new OnHitchhikeAcceptTripPlanListener() {
            @Override
            public void onSuccess() {
                setupButtons();
            }

            @Override
            public void onFailure(Throwable throwable) {
                ToastUtils.show(GlobalContext.getGlobalContext(), TextUtils.getThrowableMessage(throwable));
            }
        });
    }

    @OnClick(R.id.btn_pickup_customer)
    void onClickBtnPickup() {
        mTicket.status = TicketStatus.getInstance().START;
        HitchhikeNetworkHelper.INSTANCE.changeDriverTicketStatus(mTicket.id, mTicket.status, new OnTicketStatusChangeListener() {
            @Override
            public void onSuccess() {
                setupButtons();
            }

            @Override
            public void onFailure(Throwable throwable) {
                ToastUtils.show(GlobalContext.getGlobalContext(), TextUtils.getThrowableMessage(throwable));
            }
        });
    }

    @OnClick(R.id.btn_customer_arrive)
    void onClickBtnArrive() {
        mTicket.status = TicketStatus.getInstance().UNPAID;
        HitchhikeNetworkHelper.INSTANCE.changeDriverTicketStatus(mTicket.id, mTicket.status, new OnTicketStatusChangeListener() {
            @Override
            public void onSuccess() {

                DialogPlus.newDialog(GlobalContext.getGlobalContext())
                        .setCancelable(false)
                        .setGravity(Gravity.CENTER)
                        .setContentHolder(new ViewHolder(R.layout.dialog_hitchhike_driver_confirm))
                        .setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(final DialogPlus dialog, View view) {
                                if (view.getId() == R.id.btn_ok) {

                                    dialog.dismiss();

                                    DriverTripDetailActivity.this.startActivity(
                                            HitchhikeActivity.newIntent(HitchhikeConstants.TAG_DRIVER_RUNNING));
                                    DriverTripDetailActivity.this.finish();
                                }
                            }
                        })
                        .create().show();

                setupButtons();
            }

            @Override
            public void onFailure(Throwable throwable) {
                ToastUtils.show(GlobalContext.getGlobalContext(), TextUtils.getThrowableMessage(throwable));
            }
        });
    }

    @OnClick(R.id.btn_dialer)
    void onClickBtnDialer() {
        String phone = HitchhikeConstants.DEFAULT_PHONE_NUMBER;
        if (!android.text.TextUtils.isEmpty(customerAccount.mMobile)) {
            phone = customerAccount.mMobile;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phone));
        startActivity(intent);
    }
}
